﻿using MqttLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace remote_config_tools
{
    public class mqttlib
    {
        private IMqtt _client;
        private Form1 fm;
        public mqttlib(Form1 fm)
        {
            this.fm = fm;
        }
        public mqttlib(string addr, string port)
        {
            
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="addr"></param>
        /// <param name="port"></param>
        public void mqttConnectToServer(string addr,string port)
        {
            if (_client != null) return;

            _client = MqttClientFactory.CreateClient("tcp://" + addr + ":" + port, Guid.NewGuid().ToString().Replace("-", ""));
            try
            {
                _client.Connect(true);
            }
            catch (Exception)
            {
                return;
            }
            _client.Connected += new ConnectionDelegate(client_Connected);
            _client.ConnectionLost += new ConnectionDelegate(_client_ConnectionLost);
            _client.PublishArrived += new PublishArrivedDelegate(client_PublishArrived);
            Console.WriteLine("连接成功");
        }
        /// <summary>
        /// 
        /// </summary>
        public void mqttDisonnectToServer()
        {
            try
            {
                if (_client.IsConnected)
                {
                    _client.Disconnect();
                    _client = null;
                }
            }
            catch (Exception ex)
            {
                _client = null;
            }
            Console.WriteLine("断开成功");
        }
        /// <summary>
        /// mqtt  连接成功
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void client_Connected(object sender, EventArgs e)
        {
            Console.WriteLine("Client connected\n");
        }
        /// <summary>
        /// mqtt 连接断开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void _client_ConnectionLost(object sender, EventArgs e)
        {
            Console.WriteLine("Client connection lost\n");
        }
        /// <summary>
        /// mqtt数据到达
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        bool client_PublishArrived(object sender, PublishArrivedArgs e)
        {
            try
            {
                if (e.Payload.TrimmedBuffer[0] != 0xaa) return true;

                if (e.Payload.TrimmedBuffer[1]>240)  return true;

                byte[] recv_mqtt = new byte[256];

                ushort len = e.Payload.TrimmedBuffer[1];

                Array.Copy(e.Payload.TrimmedBuffer, 0, recv_mqtt, 0, len);

                if (recv_mqtt[len - 1] == dt_protocol.crcCalculate(recv_mqtt, len))
                {
                    //收到参数配置返回帧
                    if (recv_mqtt[12] == 0x58 && recv_mqtt[13] == 0x01)
                    {
                        int sensor_type = (int)recv_mqtt[14]* 256+ recv_mqtt[15];
                        switch (sensor_type)
                        {
                            case 0x0001:
                            case 0x0002:
                            case 0x0003:
                            case 0x0004:
                            case 0x0005:
                            case 0x0006:

                                Int16 recvDataA = (Int16)(recv_mqtt[16] * 256 + recv_mqtt[17]);
                                Int16 recvDataB = (Int16)(recv_mqtt[18] * 256 + recv_mqtt[19]);
                                Int16 recvDataC = (Int16)(recv_mqtt[20] * 256 + recv_mqtt[21]);
                                Int16 recvDataD = (Int16)(recv_mqtt[22] * 256 + recv_mqtt[23]);
                                Int16 recvDataE = (Int16)(recv_mqtt[24] * 256 + recv_mqtt[25]);

                                float recvDataAD = (float)recvDataA / 100;
                                float recvDataBD = (float)recvDataB / 100;
                                float recvDataCD = (float)recvDataC / 100;
                                float recvDataDD = (float)recvDataD / 100;
                                float recvDataED = (float)recvDataE / 100;
                                
                                fm.ctrlobj.UpTextBoxText(fm.getTextboxA(), recvDataAD.ToString("F2"));
                                fm.ctrlobj.UpTextBoxText(fm.getTextboxB(), recvDataBD.ToString("F2"));
                                fm.ctrlobj.UpTextBoxText(fm.getTextboxC(), recvDataCD.ToString("F2"));
                                fm.ctrlobj.UpTextBoxText(fm.getTextboxD(), recvDataDD.ToString("F2"));
                                fm.ctrlobj.UpTextBoxText(fm.getTextboxE(), recvDataED.ToString("F2"));

                                break;
                            default: break;
                        }
                        fm.ctrlobj.UpStatusToolCtrlText(fm.getSS(), fm.getTSS(), "参数操作","参数操作成功");
                        fm.ctrlobj.UpLabelText(fm.getParaLabel(), "参数操作成功");
                    }
                    //收到升级数据返回帧
                    else if (recv_mqtt[12] == 0x48 && recv_mqtt[13] == 0x01)
                    {
                        fileOp.cur_recv_pack_num = (long)recv_mqtt[16] * 256 + (long)recv_mqtt[17];
                        fileOp.myResetEvent.Set();
                        //fileOp.has_come = 1;
                    }
                }
            }
            catch (Exception ex)
            {

            }
            return true;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="topic"></param>
        /// <param name="mp"></param>
        /// <param name="qos"></param>
        /// <param name="retained"></param>
        public void mqttPublishSomething(string topic, byte [] mp, QoS qos, bool retained)
        {
            
            try
            {
                if (!_client.IsConnected) return;
                _client.Publish(topic, new MqttPayload(mp, 0), qos, retained);
            }
            catch (Exception ex)
            {
                _client.Disconnect();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="topic"></param>
        /// <param name="str"></param>
        /// <param name="qos"></param>
        /// <param name="retained"></param>
        public void mqttPublishSomething(string topic, string str, QoS qos, bool retained)
        {
            if ((_client == null) && (!_client.IsConnected)) return;
            try
            {
                _client.Publish(topic, str, qos, retained);
            }
            catch (Exception ex)
            {
                _client.Disconnect();
            }
        }
        public void mqttSubscribe(string topic)
        {
            try
            {
                _client.Subscribe(topic, QoS.BestEfforts);
            }
            catch (Exception ex)
            {
             
            }
    
        }
    }
}
